package net.lovesrc.allin;

import com.zhouzhou.fastjava.http.Requests;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@EnableScheduling
@SpringBootApplication
public class MyAllInApplication {

    public static void main(String[] args) {
        new Thread(() -> Requests.get("https://www.baidu.com")).start();
        ConfigurableApplicationContext context = SpringApplication.run(MyAllInApplication.class, args);
        executeJobs(context);
    }

    private static void executeJobs(ConfigurableApplicationContext context) {
        Collection<BaseJob> jobBeans = context.getBeansOfType(BaseJob.class).values();
        if (jobBeans == null || jobBeans.size() == 0) {
            return;
        }
        List<BaseJob> jobs = jobBeans.stream()
                .filter(MyAllInApplication::isNeedExecuteJob)
                .collect(Collectors.toList());
        ExecutorService jobExecutorService = Executors.newFixedThreadPool(jobs.size());
        for (BaseJob job : jobs) {
            jobExecutorService.execute(job);
        }
    }

    private static boolean isNeedExecuteJob(BaseJob r) {
        if (r.getClass().getName().contains("backup")) {
            return false;
        }
        return true;
    }

}
